package com.gordon.tips.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.gordon.tips.domain.Reply;
import com.gordon.tips.domain.Topic;
import com.gordon.tips.domain.User;
import com.gordon.tips.util.Constants;

/**
 *****************************************************************************
 ** Module : Topic data access object
 ** 
 ** Date:  Aug 14, 2011
 ** 
 ** Author: Gordon
 ** 
 ** Email: 462991284@qq.com
 ** 
 ** (C) Copyright 2011 Gordon's Office
 *****************************************************************************
 */
public class TopicDao extends SqlMapClientDaoSupport {
	
	public List<Topic>getTopics(int start,int pageSize)
	{
		Map<String ,Integer>map=new HashMap<String,Integer>();
		map.put("start", start);
		map.put("pageSize", pageSize);
		
		return getSqlMapClientTemplate().queryForList("getTopics", map);
	}
	
	public int countAllTopics()
	{
		return (Integer) getSqlMapClientTemplate().queryForObject("countAllTopics");
	}
	
	public Topic getTopicById(int id)
	{
		getSqlMapClientTemplate().update("updateView",id);
		return (Topic) getSqlMapClientTemplate().queryForObject("getTopicById",id);
	}
	
	public void addNewTopic(Topic topic,Reply reply,User user)
	{	
		Map<String,Object>map2=new HashMap<String,Object>();
		map2.put("title",topic.getTitle());
		map2.put("createTime",new Date());
		map2.put("lastReplyTime",new Date());
		map2.put("authorId",user.getId());
		map2.put("lastReplyerId",user.getId());
		
		int topicId=(Integer)getSqlMapClientTemplate().insert("addNewTopic",map2);
		
		
		reply.setCreateTime(new Date());
		Map<String ,Object>map=new HashMap<String,Object>();
		map.put("content",reply.getContent());
		map.put("createTime",reply.createTime);
		map.put("floor",1);
		map.put("topicId",topicId);
		map.put("authorId",user.getId());		
		
		Map<String,Integer>map3=new HashMap<String ,Integer>();
		map3.put("score", Constants.SCORE_ADD_NEWTOPIC);
		map3.put("id", user.getId());
		
		getSqlMapClientTemplate().insert("addNewReply",map);
		getSqlMapClientTemplate().update("updateUserScore",map3);
	}
	
	/**
	 * update the topic
	 * @Author: Gordon
	 */
	public void editTopic(Topic topic)
	{
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("id",topic.getId());
		map.put("title",topic.getTitle());
		getSqlMapClientTemplate().update("editTopic",map);
	}


}
